package com.javaEE.gamepigeon.config;

import com.javaEE.gamepigeon.dao.LoginDao;
import com.javaEE.gamepigeon.entity.User;
import com.javaEE.gamepigeon.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthencationTokenFilter extends OncePerRequestFilter {
    @Autowired
    LoginDao loginDao;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = request.getHeader(tokenHeader);
        if (null!=authHeader&&authHeader.startsWith(tokenHead)){
            String authToken = authHeader.substring(tokenHead.length());
            String openid = jwtTokenUtil.getOpenIdFromToken(authToken);
            //token存在用户名但是未登录
            if(null!=openid&&null== SecurityContextHolder.getContext().getAuthentication()){
                User user = loginDao.queryUserByOpenId(openid);
                if(jwtTokenUtil.validToken(authToken,user)){
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
